<?php

/**
 * Model Service
 *
 * @author nguyenmanhluu
 * @since Jul 26, 2013 - 4:39:23 PM
 * 
 * This is the model class for table "{{service}}".
 *
 * The followings are the available columns in table '{{service}}':
 * @property integer $sid
 * @property integer $category_id
 * @property string $s_name
 * @property string $duration
 * @property double $price
 * @property string $recover
 * @property string $description
 * @property integer $book_online
 * @property string $images
 * @property string $avatar
 * @property string $address
 * @property string $address2
 * @property string $postal_code
 * @property string $latitude
 * @property string $longitude
 * @property integer $status
 * @property integer $type
 * @property integer $author_id id cua merchant duoc gan vao
 * @property integer $travel
 * @property integer $weight
 */
class Service extends CActiveRecord
{

    const TYPE_SERVICE          = 0;
    const TYPE_ROOM             = 1;
    const ACTIVE                = 1;
    const BLOCK                 = 0;
    //Type book online
    const BOOKING_OFFLINE       = 0;
    const BOOKING_OFFICE        = 1;
    const BOOKING_CUSTOMER_HOME = 2;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Service the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{service}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('category_id, s_name, duration, recover, type, author_id', 'required'),
            array('category_id, book_online, status, type, author_id, travel', 'numerical', 'integerOnly' => true),
            array('price', 'numerical'),
            array('address, address2, postal_code, s_name', 'length', 'max' => 255),
            array('images, description,longitude , latitude, address, address2, postal_code, weight', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('sid ,weight, longitude , latitude, address, address2, postal_code, category_id, s_name, duration, price, recover, description, book_online, images, status, type, author_id ,avatar, travel', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        return array();
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        $s_name = $this->type == Service::TYPE_ROOM ? '' : 'Service';
        $s_name .= " Name";
        return array(
            'sid'         => 'Sid',
            'category_id' => Yii::t('main', 'Category'),
            's_name'      => $s_name,
            'duration'    => Yii::t('main', 'Duration'),
            'price'       => Yii::t('main', 'Price'),
            'recover'     => Yii::t('main', 'Recover/Cleanup'),
            'description' => Yii::t('main', 'Description'),
            'book_online' => Yii::t('main', 'Book Online'),
            'images'      => Yii::t('main', 'Images'),
            'avatar'      => Yii::t('main', 'Avatar'),
            'address'     => Yii::t('main', 'Address'),
            'address2'    => Yii::t('main', 'Address 2'),
            'postal_code' => Yii::t('main', 'Postal Code'),
            'latitude'    => Yii::t('main', 'Latitude'),
            'longitude'   => Yii::t('main', 'Longitude'),
            'status'      => Yii::t('main', 'Status'),
            'type'        => Yii::t('main', 'Type'),
            'author_id'   => Yii::t('main', 'Merchant'),
        );
    }

    /**
     * Retrieves a list of staff's model
     * @return CActiveDataProvider
     */
    public function getStaff()
    {
        $service_staff = ServiceStaff::model()->findAll('sid=:sid', array(':sid' => $this->sid));

        $array = array();

        if ($service_staff == NULL)
        {
            return NUll;
        }
        else
        {
            foreach ($service_staff as $sv)
            {
                $array[] = Users::getRecordByUkey($sv->sukey);
            }

            return $array;
        }
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on
     * the search/filter conditions.
     * @return CActiveDataProvider
     */
    public function search()
    {
// Warning: Please modify the following code to remove attributes that
// should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('sid', $this->sid);
        $criteria->compare('category_id', $this->category_id);
        $criteria->compare('s_name', $this->s_name, true);
//        $criteria->compare('duration', $this->duration, true);
//        $criteria->compare('price', $this->price);
//        $criteria->compare('recover', $this->recover, true);
//        $criteria->compare('description', $this->description, true);
//        $criteria->compare('book_online', $this->book_online);
//        $criteria->compare('images', $this->images, true);
//        $criteria->compare('images', $this->avatar, true);
//        $criteria->compare('address', $this->address, true);
//        $criteria->compare('address2', $this->address2, true);
//        $criteria->compare('postal_code', $this->postal_code, true);
//        $criteria->compare('latitude', $this->latitude, true);
//        $criteria->compare('longitude', $this->longitude, true);
//        $criteria->compare('status', $this->status);
//        $criteria->compare('type', $this->type);
//        $criteria->compare('author_id', $this->author_id);
//        $filterBusiness=null;
        if (($type = Yii::app()->request->getQuery('type', -1)) != -1)
        {
            $criteria->compare('type', $type);
        }
        else
            $criteria->compare('type', Service::TYPE_SERVICE);

        if (($name = Yii::app()->request->getQuery('s_name', '')) != '')
        {
            $criteria->compare('s_name', $name, true);
        }
        $filterBusiness = '';

        if (user()->isMerchant())
        {
            //select toan bo room thuoc biz quan ly
//            $criteria->condition = 'type=:t AND author_id=:a';
//            $criteria->params = array(
//                ':t' => $type,
//                ':a' => Yii::app()->user->id
//            );
            $list_branch_ids = Merchant::get_id_all_branch(user()->id, TRUE);
            $criteria->addInCondition('author_id', $list_branch_ids);
            #$filterBusiness = Users::getUkeyById(Yii::app()->user->id);
        }
        elseif (user()->isBranch())
        {
            $criteria->compare('author_id', user()->id);
        }
        elseif (user()->isAdmin())
        {
            if (isset($_GET['pk']))
            {
                $filterBusiness = $_GET['pk'];
            }

            if ($filterBusiness)
            {
                $criteria->compare('author_id', Users::getIdByUkey($filterBusiness));
            }
            if ($this->author_id != 0)
                $criteria->compare('author_id', $this->author_id);
//            else
//            {
            #$criteria->compare('type',$type,true);
//                $criteria->condition = 'type=:t AND author_id=:a';
//                $criteria->params = array(
//                    ':t' => $type,
//                    ':a' => Users::getIdByUkey($filterBusiness)
//                );
//            }
        }
//        $criteria->compare('travel', $this->travel);
        return new CActiveDataProvider($this, array(
            'criteria'   => $criteria,
            'pagination' => array(
                'pageSize' => 30,
            ),
            'sort'       => array(
                'attributes' => array('s_name', 'category_id')
            )
        ));
    }

    public function getHotdealUrlLabel()
    {
        $url = Yii::app()->createUrl('hotdeal/modify', array('sv' => $this->sid));
        return $this->hotdeal ? "<a href='$url' class='btn'>Added</a>" : "<a href='$url' class='btn btn-success'>Add hotdeal</a>";
    }

    public function getThefirstDiscount($value = false)
    {
        if (Yii::app()->user->isGuest)
        {
            if ($this->thefirst != NULL)
                return true;
            else
                return false;
        }else
        {
            $user = Yii::app()->getCurrentUser();
            if ($user == NULL || $user->isCustomer != true)
                return false;
            else
            {
                $merchant = $this->user;
                $customer = Customer::checkCustomerBelongToBiz($user->id, $merchant->id);
                if ($customer == false && $this->thefirst != NULL)
                {
                    if ($value == false)
                    {
                        $time = time();
                        if ($this->thefirst->start_time >= $time && $this->thefirst->end_time <= $time)
                        {
                            $current_time        = date("H:i:s", time());
                            $today               = getdate();
                            $current_day         = $today['wday'];
                            $criteria            = new CDbCriteria();
                            $criteria->condition = "start_time_value =< '" . $current_time . "' and end_time_value>='" . $current_time . "'";
                            $thefirst_period     = ThefirstPeriod::model()->findByAttributes(array('thefirst_id' => $this->thefirst->id, 'day_of_week' => $current_day), $criteria);
                            if ($thefirst_period != NULL)
                                return true;
                            else
                                return false;
                        }
                        else
                            return false;
                    }else
                    {
                        
                    }
                }
                else
                    return false;
            }
        }
    }

    public static function BookingTypeArray()
    {
        return array(
            self::BOOKING_OFFLINE       => Yii::t('main', 'Booking Offline'),
            self::BOOKING_OFFICE        => Yii::t('main', 'Booking at Office'),
            self::BOOKING_CUSTOMER_HOME => "Booking at Customer's Home",
        );
    }

    public function getBookingType()
    {
        $arr = self::BookingTypeArray();
        return $arr[$this->book_online];
    }

    public static function getDurationArray()
    {
        return self::get5minArray();
    }

    public static function getNumbersOfService()
    {

        $criteria = new CDbCriteria();

        if (Yii::app()->user->isMerchant())
        {
            $criteria->condition = 'author_id=:author_id';
            $criteria->params    = array(':author_id' => Yii::app()->user->getId());
        }

        $count = Service::model()->count($criteria);
        return $count;
    }

    /**
     * Get biz
     * @return CACTIVERECORD
     */
    public function getBiz()
    {
        $staff_service = ServiceStaff::model()->find('sid=:sid', array(':sid' => $this->sid));
        if ($staff_service)
        {
            $biz = Users::getBizbyUkeyStaff($staff_service->sukey);
            return $biz;
        }
        return NULL;
    }

    /**
     * Get a service record by ID
     * @param int $sid Service ID
     * @return mixed <b>NULL</b> or <b> a single record </b> return
     */
    public static function getRecordbySid($sid)
    {
        return Service::model()->findByPk($sid);
    }

    public static function getRecoverArray()
    {
        return self::get5minArray();
    }

    public static function get5minArray()
    {
        $ret = array();
        for ($i = 0; $i <= 300; $i+=5)
        {
            $time = '';
            $h    = floor($i / 60);
            $m    = $i % 60;

            // No show hour
            if ($h == 0)
            {
                $time = "";
            }
            elseif ($h == 1)
            {
                $time = "1 hour";
            }
            else
            {
                $time = "$h hours";
            }

            if ($m == 0)
            {
                // O hour 0 minutes => show 0
                if ($h == 0)
                {
                    $time = 0;
                }
            }
            else
            {
                $time .= " $m minutes";
            }

            $ret[$i] = $time;
        }
        return $ret;
    }

    /**
     * @return string url service's detail page at homepgae
     */
    public function getDetailUrl()
    {
        return Yii::app()->createUrl('frontend/detail/index', array('service' => $this->sid));
    }

    public function getBookingUrl()
    {
        /**
         * TODO: by Brian Nguyen, use the next 4 comments when new url is applied.
         */
        return Yii::app()->createUrl('frontend/booking/index', array('service' => $this->sid));
//        $business=Business::model()->findByAttributes(array('user_id'=>$this->author_id));
//        if(!$business)
//            return '';
//        return Yii::app()->createUrl('frontend/booking/index', array('biz' => $business->biz_url,'sUrl'=>$this->alias));
    }

    public function getAbsoluteBookingUrl()
    {
        $business = Business::model()->findByAttributes(array('user_id' => $this->author_id));
        if (!$business)
            return '';
        return Yii::app()->createAbsoluteUrl('frontend/booking/index', array('biz' => $business->biz_url, 'sUrl' => $this->alias));
    }

    public function getPublicImage()
    {
        if ($this->defaultImage)
            return Yii::app()->baseUrl . "/" . $this->defaultImage->image;
        else
            return Yii::app()->controller->assetDir . '/img/no-image.png';
    }

    public function getRatio16_9Image()
    {
//        return '';
        if (!$this->defaultImage)
        {
            return Yii::app()->controller->assetDir . '/img/no-image.png';
        }
        $file = Yii::getPathOfAlias('webroot') . '/' . $this->defaultImage->image;


        $path_parts = pathinfo($file);
        $extesion   = $path_parts['extension'];

        $new_name  = $path_parts['filename'] . "_w400h225";
        $path_save = Yii::getPathOfAlias('webroot') . '/files/service/';



        if (!file_exists($path_save . $new_name . '.' . $extesion))
        {

            $thumb = Yii::app()->phpThumb->create($file);

            $thumb->adaptiveResize(400, 225);
            $thumb->save($path_save . '/' . $new_name . '.' . $extesion);
        }
        return Yii::app()->baseUrl . '/files/service/' . $new_name . '.' . $extesion;
    }

    public function getFullLinkImage()
    {
        if ($this->defaultImage)
            return Yii::app()->createAbsoluteUrl($this->defaultImage->image);
        else
            return Yii::app()->controller->assetDir . '/img/no-image.png';
    }

    public function get_avatar_by_size($w, $h)
    {
        if (!$this->avatar)
        {
            return Yii::app()->controller->assetDir . '/img/no-image.png';
        }


        $file = Yii::getPathOfAlias('webroot') . '/' . $this->avatar;
        $path = Yii::getPathOfAlias('webroot') . '/files/service/';

        if (!file_exists($file))
        {
            return Yii::app()->controller->assetDir . '/img/no-image.png';
        }

        $path_parts = pathinfo($file);

        $extesion  = $path_parts['extension'];
        $file_name = $path_parts['filename'] . "_w" . $w . 'h' . $h . '.' . $extesion;

        if (!file_exists($path . $file_name) AND ! is_file($path . $file_name))
        {

            $thumb = Yii::app()->phpThumb->create($file);
            $thumb->adaptiveResize($w, $h);
            $thumb->save($path . '/' . $file_name);
        }

        return Yii::app()->baseUrl . '/files/service' . '/' . $file_name;
    }

    /**
     * 
     * @return tring 
     */
    public function getPublicAvatar()
    {
        if ($this->avatar)
            return Yii::app()->baseUrl . "/" . $this->avatar;
        else
            return Yii::app()->controller->assetDir . '/img/no-image.png';
    }

    /**
     * @since 17.Jan.2014
     * @return string
     */
    public function getEditUrl()
    {
        $action = "edit";
        $action .= $this->type == self::TYPE_ROOM ? 'Room' : 'Service';
        return Yii::app()->createUrl("service/update", array('id' => $this->sid));
    }

    public function getDeleteUrl()
    {
        $action = "delete";
        $action .= $this->type == self::TYPE_ROOM ? 'Room' : 'Service';
        return Yii::app()->createUrl("service/$action", array('pk' => $this->sid));
    }

    /**
     * @return array array services`
     */
    public static function getServices()
    {
        $cri  = new CDbCriteria();
        $user = Users::model()->findByPk(Yii::app()->user->getId());
        if (Yii::app()->user->isAdmin())
        {
            
        }
        elseif (Yii::app()->user->isMerchant())
        {
            $cri->with = array('user');
            $cri->compare('user.id', $user->id);
        }
        elseif (Yii::app()->user->isStaff())
        {
            $staff_ukey     = Yii::app()->user->currentUser->ukey;
            $service_staffs = ServiceStaff::model()->findAll('sukey=:s', array(':s' => $staff_ukey));
            $arr            = array();
            foreach ($service_staffs as $service_staff)
            {
                $arr[] = $service_staff->sid;
            }

            $cri->addInCondition('sid', $arr);
        }
        $model = self::model()->findAll($cri);

        $arr = array();

        foreach ($model as $s)
        {
            $arr[$s->sid] = $s->s_name;
        }

        return $arr;
    }

    /**
     * 
     * @param type $cat_id
     */
    public static function getArrServiceBycategory($cateid, $type = Service::TYPE_SERVICE)
    {
        $model = self::model()->findAll('category_id=:c AND type=:t', array(
            ':t' => $type,
            ':c' => $cateid,
        ));

        $arr = array();

        if ($model != NULL)
        {

            foreach ($model as $s)
            {
                $arr[$s->sid] = $s->s_name;
            }
        }

        return $arr;
    }

    /**
     * @return html array services 
     */
    public static function getServicesBycategory($cateid, $type = Service::TYPE_SERVICE)
    {

        $model = self::model()->findAll('category_id=:c AND type=:t', array(
            ':t' => $type,
            ':c' => $cateid,
        ));

        $html = '<option >Chose one...</option>';

        if ($model != NULL)
        {

            foreach ($model as $s)
            {
                $html.='<option value="' . $s->sid . '">' . $s->s_name . '</option>';
            }
        }

        return $html;
    }

    /**
     * 
     */
    public function getTotalTime()
    {
        return $this->durationTime + $this->recover;
    }

    public function getDurationTime()
    {
        $duration = self::getDurationArray();
        return (isset($duration[$this->duration])) ? $duration[$this->duration] : '';
    }

    public function getPriceFormat()
    {
        return number_format($this->price, 2);
    }

    public function getCountFavour()
    {
        $favourites = Favourite::model()->findAll('sid=:s', array(
            ':s' => $this->sid
        ));
        if ($favourites)
        {
            return count($favourites);
        }
        else
        {
            return 0;
        }
    }

    public function getAsoluteUrl()
    {
        return Yii::app()->createAbsoluteUrl('frontend/detail/index', array('service' => $this->sid));
    }

    public function getShortLink()
    {
        $long_url = $this->getAsoluteUrl();

        $bitly = Yii::app()->bitly->shorten($long_url)->getResponseData();



        $encode = json_decode($bitly, true);

        if ($encode->status_code == 200)
        {
            return $encode->data->url;
        }
    }

    public function getFullAddress()
    {
        if ($this->address)
        {
            return $this->address . ' ' . $this->postal_code;
        }
        else
        {
            return $this->user->fullAddress;
        }
    }

    public function getPublicImage350()
    {
        if (!$this->defaultImage)
        {
            return Yii::app()->controller->assetDir . '/img/no-image.png';
        }

        $file       = Yii::getPathOfAlias('webroot') . '/' . $this->defaultImage->image;
        list($w) = getimagesize($file);
        $percent    = round(350 / $w * 100);
        $dir_name   = dirname($file);
        $path_parts = pathinfo($file);
        $file_name  = $path_parts['filename'] . "_w350.jpg";
        if (!file_exists($file_name))
        {
            $thumb = Yii::app()->phpThumb->create($file);
            $thumb->resizePercent($percent);
            $thumb->save($dir_name . '/' . $file_name);
        }
        return Yii::app()->baseUrl . '/files/service' . '/' . $file_name;
    }

    public function getPublicImage335()
    {
        if (!$this->defaultImage)
        {
            return Yii::app()->controller->assetDir . '/img/no-image.png';
        }
        $file       = Yii::getPathOfAlias('webroot') . '/' . $this->defaultImage->image;
        list($w) = getimagesize($file);
        $percent    = ceil(334 / $w * 100);
        $dir_name   = dirname($file);
        $path_parts = pathinfo($file);
        $file_name  = $path_parts['filename'] . "_w334.jpg";
        if (!file_exists($file_name))
        {
            $thumb = Yii::app()->phpThumb->create($file);
            $thumb->resizePercent($percent);
            $thumb->save($dir_name . '/' . $file_name);
        }
        return Yii::app()->baseUrl . '/files/service' . '/' . $file_name;
    }

    public function getPublicImage50()
    {

        $file       = Yii::getPathOfAlias('webroot') . '/' . $this->avatar;
        list($w) = getimagesize($file);
        $percent    = ceil(50 / $w * 100);
        $dir_name   = dirname($file);
        $path_parts = pathinfo($file);
        $file_name  = $path_parts['filename'] . "_w50.jpg";
        if (!file_exists($file_name))
        {
            $thumb = Yii::app()->phpThumb->create($file);
            $thumb->resizePercent($percent);
            $thumb->save($dir_name . '/' . $file_name);
        }
        return Yii::app()->baseUrl . '/files/service' . '/' . $file_name;
    }

    public function getImagew467()
    {
        if (!$this->defaultImage)
        {
            return Yii::app()->controller->assetDir . '/img/no-image.png';
        }

        $file = Yii::getPathOfAlias('webroot') . '/' . $this->defaultImage->image;

        if (!$this->defaultImage)
        {
            return Yii::app()->controller->assetDir . '/img/no-image.png';
        }

        $path_parts = pathinfo($file);
        $extesion   = $path_parts['extension'];

        $new_name  = $path_parts['filename'] . "_w467h200";
        $path_save = Yii::getPathOfAlias('webroot') . '/files/service/';

        if (!file_exists($path_save . $new_name . '.' . $extesion))
        {

            $thumb = Yii::app()->phpThumb->create($file);

            $thumb->adaptiveResize(467, 200);
            $thumb->save($path_save . '/' . $new_name . '.' . $extesion);
        }
        return Yii::app()->baseUrl . '/files/service/' . $new_name . '.' . $extesion;
    }

    public function getPriceAfterDiscount()
    {
        $crr_hour = date('H:i', time());
        $discount = Hotdeal::getDiscountByTime($this->sid, time(), $crr_hour);
        $price    = $this->price - $this->price * $discount / 100;
        return $price;
    }

    public function getHotdeal()
    {
        //Hidden Mimispa
        $arr_hidden_service   = ' AND tbl_service.sid NOT IN (1,3,14,15,16,17,18,19,20,289,291) ';
        $arr_hidden_service_1 = ' AND tbl_hotdeal.sid NOT IN (1,3,14,15,16,17,18,19,20,289,291) ';

        $image_large   = (isset($_POST['image_large']) && $_POST['image_large'] == 'yes') ? 1 : 0;
        $current_time  = strtotime(date('Y-m-d'));
        $query         = 'select tbl_hotdeal.sid from tbl_hotdeal LEFT JOIN tbl_service ON tbl_hotdeal.sid = tbl_service.sid where tbl_hotdeal.merchant_status = "active" and ' . $current_time . ' <= tbl_hotdeal.end_time ' . $arr_hidden_service_1 . ' ORDER BY tbl_hotdeal.id DESC limit 6'; //GROUP BY tbl_service.author_id 
        $hot_deal      = Yii::app()->db->createCommand($query)->queryAll();
        $list_hot_deal = array();
        if (count($hot_deal) > 0)
        {
            $str = '(';
            for ($i = 0; $i < count($hot_deal); $i++)
            {
                if ($i == 0)
                    $str .= $hot_deal[$i]['sid'];
                else
                    $str .= ',' . $hot_deal[$i]['sid'];
            }
            $str .= ')';
            $query_service = 'select tbl_service.s_name,tbl_service.sid,tbl_service.price,tbl_service.type,tbl_service.author_id,tbl_service_img.image from tbl_service LEFT JOIN tbl_service_img ON tbl_service.sid = tbl_service_img.service_id where sid IN ' . $str . ' and tbl_service.status = 1 and tbl_service.book_online <> 0';
            $list_hot_deal = Yii::app()->db->createCommand($query_service)->queryAll();
        }

        for ($j = 0; $j < count($list_hot_deal); $j++)
        {
            $list_hot_deal[$j]['price'] = number_format($list_hot_deal[$j]['price'], 2);
            if ($image_large == 0)
            {
                $list_hot_deal[$j]['image_url'] = $this->getImageService50($list_hot_deal[$j]['image']);
            }
            else
            {
                $list_hot_deal[$j]['image_url'] = $this->getImageService400x225($list_hot_deal[$j]['image']);
            }
            $query_hotdeal                 = 'select round(max(discount)) as max_dis from tbl_hotdeal_period INNER JOIN tbl_hotdeal on tbl_hotdeal_period.hotdeal_id = tbl_hotdeal.id where tbl_hotdeal.merchant_status = "active" and ' . $current_time . ' <= tbl_hotdeal.end_time and tbl_hotdeal.sid =' . $list_hot_deal[$j]['sid'];
            $max_discount                  = Yii::app()->db->createCommand($query_hotdeal)->queryAll();
            if ($max_discount != NULL)
                $list_hot_deal[$j]['hot_deal'] = $max_discount[0]['max_dis'];
            $query_merchant                = 'select tbl_users.business_name,tbl_business.biz_url from tbl_users join tbl_business on tbl_users.id = tbl_business.user_id where tbl_users.id =' . $list_hot_deal[$j]['author_id'];
            $merchant                      = Yii::app()->db->createCommand($query_merchant)->queryAll();
            if (count($merchant) > 0)
            {
                $list_hot_deal[$j]['merchant'] = $merchant[0];
            }
        }
        return $list_hot_deal;
    }

    public function getOtherService()
    {
        //Hidden Mimispa
        $arr_hidden_service   = ' AND tbl_service.sid NOT IN (1,3,14,15,16,17,18,19,20,289,291) ';
        $arr_hidden_service_1 = ' AND tbl_hotdeal.sid NOT IN (1,3,14,15,16,17,18,19,20,289,291) ';

        $image_large  = (isset($_POST['image_large']) && $_POST['image_large'] == 'yes') ? 1 : 0;
        $current_time = strtotime(date('Y-m-d'));
        $merchant_id  = (isset($_POST['mid']) && is_numeric($_POST['mid']) ) ? $_POST['mid'] : -1;
        $sql_mc       = '';
        if ($merchant_id != -1)
        {
            $sql_mc = ' and tbl_service.author_id = ' . $merchant_id;
        }
        $query_hotdeal = '(select round(max(discount)) as max_dis,tbl_hotdeal.sid from tbl_hotdeal_period JOIN tbl_hotdeal on tbl_hotdeal_period.hotdeal_id = tbl_hotdeal.id where tbl_hotdeal.merchant_status = "active" and ' . $current_time . ' <= tbl_hotdeal.end_time group by tbl_hotdeal.id) as A';
        $query_service = '(select tbl_service.s_name,tbl_service.sid,tbl_service.price,tbl_service.type,tbl_service_img.image,tbl_users.business_name from tbl_service LEFT JOIN tbl_service_img ON tbl_service.sid = tbl_service_img.service_id LEFT JOIN tbl_users ON tbl_service.author_id = tbl_users.id where tbl_service.status = 1  ' . $sql_mc . $arr_hidden_service . ' and tbl_service.book_online <> 0 ORDER BY RAND() limit 6) as B';
        $query         = 'select *,B.sid as sid from ' . $query_service . ' LEFT JOIN ' . $query_hotdeal . ' on B.sid = A.sid';
        $list_services = Yii::app()->db->createCommand($query)->queryAll();
        foreach ($list_services as $key => $ls)
        {
            $list_services[$key]['price'] = number_format($ls['price'], 2);
            if ($image_large == 0)
            {
                $list_services[$key]['image_url'] = $this->getImageService50($ls['image']);
            }
            else
            {
                $list_services[$key]['image_url'] = $this->getImageService400x225($ls['image']);
            }
        }
        return $list_services;
    }

    public function getSimiService()
    {
        //Hidden Mimispa
        $arr_hidden_service   = ' AND tbl_service.sid NOT IN (1,3,14,15,16,17,18,19,20,289,291) ';
        $arr_hidden_service_1 = ' AND tbl_hotdeal.sid NOT IN (1,3,14,15,16,17,18,19,20,289,291) ';

        $current_time = strtotime(date('Y-m-d'));
        $cid          = (isset($_POST['cid']) && is_numeric($_POST['cid']) ) ? $_POST['cid'] : -1;
        $sid          = (isset($_POST['sid']) && is_numeric($_POST['sid']) ) ? $_POST['sid'] : -1;
        $sql_sv       = '';
        if ($sid != -1)
        {
            $sql_sv = ' and tbl_service.sid <> ' . $sid;
        }
        $sql_ct = '';
        if ($cid != -1)
        {
            $sql_ct = ' and tbl_service.category_id = ' . $cid;
        }

        $query_hotdeal = '(select max(discount) as max_dis,tbl_hotdeal.sid from tbl_hotdeal_period JOIN tbl_hotdeal on tbl_hotdeal_period.hotdeal_id = tbl_hotdeal.id where tbl_hotdeal.merchant_status = "active" and ' . $current_time . ' <= tbl_hotdeal.end_time group by tbl_hotdeal.id) as A';
        $query_service = '(select tbl_service.s_name,tbl_service.sid,tbl_service.price,tbl_service.type,tbl_service_img.image,tbl_users.business_name from tbl_service LEFT JOIN tbl_service_img ON tbl_service.sid = tbl_service_img.service_id LEFT JOIN tbl_users ON tbl_service.author_id = tbl_users.id where tbl_service.status = 1 ' . $sql_sv . $sql_ct . $arr_hidden_service . ' and tbl_service.book_online <> 0 ORDER BY RAND() limit 6) as B';
        $query         = 'select *,B.sid as sid from ' . $query_service . ' LEFT JOIN ' . $query_hotdeal . ' ON B.sid = A.sid';
        $list_services = Yii::app()->db->createCommand($query)->queryAll();
        foreach ($list_services as $key => $ls)
        {
            $list_services[$key]['price']     = number_format($ls['price'], 2);
            $list_services[$key]['image_url'] = $this->getImageService50($ls['image']);
        }
        return $list_services;
    }

    public function getImageService50($img_url)
    {
        if ($img_url == '' || $img_url == NULL)
        {
            $img_url = '/themes/frontend/assets/img/no-image.png';
            $file    = Yii::getPathOfAlias('webroot') . $img_url;
        }
        else
        {
            $file = Yii::getPathOfAlias('webroot') . '/' . $img_url;
            if (FALSE == file_exists($file))
            {
                $file = Yii::getPathOfAlias('webroot') . '/themes/frontend/assets/img/no-image.png';
            }
        }
        $path_parts = pathinfo($file);
        $extesion   = $path_parts['extension'];
        $new_name   = $path_parts['filename'] . "_50";
        $path_save  = Yii::getPathOfAlias('webroot') . '/files/bizGal/';

        if (!file_exists($path_save . $new_name . '.' . $extesion))
        {
            $thumb = Yii::app()->phpThumb->create($file);
            $thumb->adaptiveResize(50, 50);
            $thumb->save($path_save . '/' . $new_name . '.' . $extesion);
        }
        return Yii::app()->baseUrl . '/files/bizGal/' . $new_name . '.' . $extesion;
    }

    public function getImageService400x225($img_url)
    {
        if ($img_url == '' || $img_url == NULL)
        {
            $img_url = '/themes/frontend/assets/img/no-image.png';
            $file    = Yii::getPathOfAlias('webroot') . $img_url;
        }
        else
        {
            $file = Yii::getPathOfAlias('webroot') . '/' . $img_url;
        }
        $path_parts = pathinfo($file);
        $extesion   = $path_parts['extension'];
        $new_name   = $path_parts['filename'] . "_w400h225";
        $path_save  = Yii::getPathOfAlias('webroot') . '/files/bizGal/';
        if (!file_exists($path_save . $new_name . '.' . $extesion))
        {
            $thumb = Yii::app()->phpThumb->create($file);
            $thumb->adaptiveResize(400, 225);
            $thumb->save($path_save . '/' . $new_name . '.' . $extesion);
        }
        return Yii::app()->baseUrl . '/files/bizGal/' . $new_name . '.' . $extesion;
    }

    /**
     * Use at: /search/_gallery_profile.php , _list_profile.php
     * @param int $width
     * @param int $height
     * @return string url of image
     */
    public function getImageBySize($width, $height)
    {

        if ($this->images == NULL or $this->images == '')
        {
            return Yii::app()->controller->assetDir . 'img/no-image.png';
        }

        if ($this->defaultImage == NULL)
        {
            return Yii::app()->controller->assetDir . 'img/no-image.png';
        }

        $file = Yii::getPathOfAlias('webroot') . '/' . $this->defaultImage->image;
        $path = Yii::getPathOfAlias('webroot') . '/files/service/';

        if (!file_exists($file) AND ! is_file($file))
        {
            return Yii::app()->controller->assetDir . 'img/no-image.png';
        }

        $path_parts = pathinfo($file);

        $extesion  = $path_parts['extension'];
        $file_name = $path_parts['filename'] . "_w" . $width . 'h' . $height . '.' . $extesion;

        //if file not exist
        if (!file_exists($path . $file_name) AND ! is_file($path . $file_name))
        {


            $thumb = Yii::app()->phpThumb->create($file);
            $thumb->adaptiveResize($width, $height);

            if ($thumb->save($path . $file_name))
            {
                return Yii::app()->baseUrl . '/files/service' . '/' . $file_name;
            }
            else
            {
                return Yii::app()->controller->assetDir . '/img/no-image.png';
            }
        }

        return Yii::app()->baseUrl . '/files/service' . '/' . $file_name;
    }

    public function get_absolute_image_url_by_size($width, $height)
    {
        return Yii::app()->getBaseUrl(true) . $this->getImageBySize($width, $height);
    }

    /**
     * Get average rewiew point of service
     * @param int $sid
     * @return float
     */
    public function getAverageReviewPoint()
    {
        $reviews = Review::model()->findAll("sid=$this->sid");

        if (!$reviews)
            return 0;

        $total_point = 0;
        foreach ($reviews as $review)
        {
            $total_point += $review->average;
        }

//        return $total_point;
        $avr = $this->allReviewCount != 0 ? $total_point / $this->allReviewCount : 0;

        return ($avr != 0) ? ceil($avr * 2) / 2 : 0;
    }

    /**
     * 
     */
    public function drawStart()
    {
        $start = $this->getAverageReviewPoint();

        $html = '';
        if ($start > 0)
        {
            for ($index = 1; $index <= 5; $index++)
            {
                if ($index <= $start)
                {
                    $html.='<i class="webmaster-icon webmaster-icon-voted"></i>';
                }
                elseif (($index - 0.5) == $start)
                {
                    $html.='<i class="webmaster-icon webmaster-icon-half"></i>';
                }
                else
                {
                    $html.='<i class="webmaster-icon webmaster-icon-unvote"></i>';
                }
            }
            $html.='<br><span class="vote-count">(' . $this->allReviewCount . ' ratings)</span>';
        }
        else
        {
            for ($index = 0; $index < 5; $index++)
            {
                $html.='<i class="webmaster-icon webmaster-icon-unvote"></i>';
            }
        }

        return $html;
    }

    public function getReviewSuggestionCount()
    {
        return Review::model()->count("sid=$this->sid AND suggestion=1");
    }

    public function getRequestServiceUrl()
    {
        return Yii::app()->createUrl('frontend/booking/RequestService', array(
                    'mid'     => $this->author_id, 'service' => $this->sid));
    }

    //return max price of total service
    public static function getMaxPrice()
    {
        $command = Yii::app()->db->createCommand('SELECT max( price ) AS maxprice FROM `tbl_service`')->queryAll();
        return $command != NULL ? floor($command[0]['maxprice']) : 500;
    }

    public function getServicePoint()
    {
        if ($this->user != null && $this->user->service != null)
        {
            return $this->price * $this->user->service->money_to_points;
        }
        return 0;
    }

    public $maxdiscount;

    /**
     * Use for browser page
     * @return float 0: not setting, 
     */
    public function get_max_1st($sid)
    {

        $crite            = new CDbCriteria();
        $crite->select    = array('sid', 'id', 'start_time', 'end_time', 'sid');
        $crite->condition = 'start_time < ' . time() . ' AND end_time >' . time() . ' AND sid=:sid';
        $crite->params    = array(':sid' => $sid);

        $t_first = Thefirst::model()->find($crite);

        if (NULL == $t_first)
        {
            return 0;
        }
        else
        {
            //find max discount
//            if(NULL!=$the_first_period ){
            $query_sql = "SELECT MAX(`discount`) AS maxdiscount FROM `tbl_thefirst_period` WHERE `thefirst_id` = $t_first->id";
            $command   = Yii::app()->db->cache(2000)->createCommand($query_sql)->queryAll();
            if ($command != NULL)
            {
                return $command[0]['maxdiscount'];
            }
            else
            {
                return 0;
            }

//            }
        }
    }

}

/**
 * End file Service
 */
